import { readableStreamToText } from "bun";
import { SourceMap } from "./SourceMap";
import { StackTrace } from "./StackTrace";
import { transform } from "./lib";

async function mapping(j : any){
    let st = StackTrace.create(j.stack)
    let mapurl = j.map as string
    let r = await fetch(mapurl)
    if(r.status != 200) throw new Error('fetch error: '+ mapurl)
    let sm = await SourceMap.create(await r.text(), 'web-mobile/assets/main/index.js')
    let t = JSON.stringify(transform([sm!], st))
    //console.log('!!! tt', t)
    t = t.replaceAll(/(\(|\")[\.\w:\/]+client\/assets\//g, '$1')
    return t
}
const port = Bun.env.PORT || 8000
let runWeb = true
if(Bun.argv[2]=='c'){
    readFromStdin()
    runWeb = false
}

async function readFromStdin() {
    let d = ''
    for await (const chunk of Bun.stdin.stream()) {
        d += Buffer.from(chunk).toString();
    }
    let t = await mapping(JSON.parse(d))
    console.log(t)
}
if(runWeb){
    console.log('!!! start port:', port)
}
runWeb && Bun.serve({
    async fetch(req) {
        console.log(req.url)
        if(req.url.match(/.*\/stack$/)){
            const proc = Bun.spawn('/root/.bun/bin/bun run index.ts c'.split(' '), {
                stdin: 'pipe',
            })
            proc.stdin.write(await req.text())
            proc.stdin.flush()
            proc.stdin.end()
            let t = await readableStreamToText(proc.stdout)
            return new Response(t)
        }
        return new Response("ok!");
    },
    port,
});